use std::io;

/// Menu
/// 
/// This is a console tool
/// 
/// It can receive a menu list and display it in the form of menu.
/// 
/// When the user uses the keyboard to make a choice, it will return user's choice.
/// 
/// It contains a loop, so it returns the value entered by the user only if the user enters a correct number

pub fn menu(menu_list: Vec<&str>) -> i32 {
    let num;

    loop{
        // Display menu
        for (index, item) in menu_list.iter().enumerate() {
            println!("{}.{}", index+1, item);
        }
        println!("0.Quit");
        print!("Please input your choice：");

        // Get user input
        let mut choice = String::new();
        io::stdin()
            .read_line(&mut choice)
            .expect("Input error");

        num = match choice
            .trim()
            .parse::<i32>() {
            Ok(num) => {
                if num > menu_list.len() as i32 {
                    println!("Menu index out of range.");
                    continue;
                }else{
                    num
                }
            },
            Err(_) => {
                println!("Input error.");
                continue;
            },
        };
        break;
    }
    num
}